<?php
declare(strict_types=1);
namespace Hangpu888\Hpadmin\controller;

use Hangpu888\Hpadmin\Controller;
use Hangpu888\Hpadmin\model\Admin;
use Hangpu888\Hpadmin\model\AdminRole;
use Hangpu888\Hpadmin\model\AuthRule;
use Hangpu888\Hpadmin\utils\builder\FormBuilder;
use Hangpu888\Hpadmin\utils\builder\ListBuilder;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\utils\manager\DataManager;
use Hangpu888\Hpadmin\validate\AdminRole as ValidateAdminRole;

class Role extends Controller
{
    public function index()
    {
        $limit = request()->get('limit',30);
        $page = request()->get('page',1);
        $is_system = ['否', '是'];
        $list = AdminRole::paginate([
            'page'          => $page,
            'list_rows'     => $limit
        ])
        ->each(function($item){
            // 系统管理员禁止删除
            $item->btnAttr = [
                'edit'      => [
                    'show'  => $item->is_system ? false : true
                ],
                'del'    => [
                    'show'  => $item->is_system ? false : true
                ],
                'auths'    => [
                    'show'  => $item->is_system ? false : true
                ],
            ];
            return $item;
        })
        ->toArray();
        if ($list['data']) {
            foreach ($list['data'] as $key => $value) {
                $list['data'][$key]['is_system_text'] = $is_system[$value['is_system']];
            }
        }
        $builder = new ListBuilder;
        $data = $builder
            ->addColumn('rightButtonList', '操作', [
                'type'              => 'template',
                'template'          => 'rightButtonList',
                'width'             => '230'
            ])
            ->addTopButton('add', '添加', [
                'api'               => '/hpadmin/Role/add',
                'title'             => '添加职位',
                'method'            => 'get',
                'type'              => 'modal',
            ])
            ->addRightButton('auths', '授权', [
                'api'               => '/hpadmin/Role/auths',
                'title'             => '职位授权',
                'method'            => 'get',
                'type'              => 'modal',
            ], [
                'type'              => 'text',
            ])
            ->addRightButton('edit', '编辑', [
                'api'               => '/hpadmin/Role/edit',
                'title'             => '修改职位',
                'method'            => 'get',
                'type'              => 'modal',
            ], [
                'type'              => 'text',
            ])
            ->addRightButton('del', '删除', [
                'api'               => '/hpadmin/Role/del',
                'method'            => 'delete',
                'title'             => '温馨提示',
                'content'           => '是否确认删除该数据？',
                'type'              => 'confirm',
            ], [
                'type'              => 'text',
            ], [
                'type'              => 'warning',
            ])
            ->addColumn('id', '序号', [
                'width'         => '80'
            ])
            ->addColumn('ctime', '创建时间')
            ->addColumn('utime', '更新时间')
            ->addColumn('title', '职位名称')
            ->addColumn('is_system_text', '禁止删除')
            ->setData($list['data'])
            ->setDataPage($list['total'], $list['last_page'], $list['per_page'], $list['current_page'])
            ->create();
        return Json::successRes($data);
    }

    /**
     * 添加/视图
     *
     * @return void
     */
    public function add()
    {
        try {
            if (request()->method() == 'POST') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateAdminRole,$post);
    
                //数据入库
                $groupModel = new AdminRole;
                foreach ($post as $field => $value) {
                    if ($value) {
                        $groupModel->$field = $value;
                    }
                }
                if ($groupModel->save()) {
                    return Json::success('添加成功');
                } else {
                    return Json::fail('添加失败');
                }
            } else {
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('post')
                    ->addRow('title', 'input', '职位名称')
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 编辑/视图
     *
     * @return void
     */
    public function edit()
    {
        try {
            $id = request()->input('id');
            if (request()->method() == 'PUT') {
                // 获取数据
                $post = request()->post();
    
                // 数据验证
                hpValidate(new ValidateAdminRole,$post);
    
                // 数据入库
                $groupModel = AdminRole::where(['id' => $id])->find();
                if (!$groupModel) {
                    return Json::fail('职位不存在');
                }
                foreach ($post as $field => $value) {
                    $groupModel->$field = $value;
                }
                if ($groupModel->save()) {
                    return Json::success('修改成功');
                } else {
                    return Json::fail('修改失败');
                }
            } else {
                $response = AdminRole::where(['id' => $id])->find()->toArray();
                $builder = new FormBuilder;
                $data = $builder
                    ->setMethod('put')
                    ->addRow('title', 'input', '职位名称')
                    ->setFormData($response)
                    ->create();
                return Json::successRes($data);
            }
        } catch (\Throwable $e) {
            return Json::fail($e->getMessage());
        }
    }

    /**
     * 删除
     *
     * @return void
     */
    public function del()
    {
        $id = request()->get('id');
        $roleModel = AdminRole::where(['id' => $id])->find();
        if (!$roleModel) {
            return Json::fail('职位不存在');
        }
        $adminModel = Admin::where(['role_id' => $roleModel->id])->find();
        if ($adminModel) {
            return Json::fail('职位下有管理员，禁止删除');
        }
        if ($roleModel->delete()) {
            return Json::success('删除成功');
        } else {
            return Json::fail('删除失败');
        }
    }

    /**
     * 角色授权
     *
     * @return void
     */
    public function auths()
    {
        $id = request()->get('id');
        if (request()->method() == 'PUT') {
            $post = request()->post();
            $roleModel = AdminRole::where(['id' => $id])->find();
            if (!$roleModel) {
                return Json::fail('找不到该数据');
            }
            $roleModel->rule = $post['rule'];
            if ($roleModel->save()) {
                return Json::success('授权成功');
            } else {
                return Json::fail('授权失败');
            }
        } else {
            $info = AdminRole::where(['id' => $id])->find();
            if (!$info) {
                return Json::fail('找不到该数据');
            }
            $info = $info->toArray();
            $rule = AuthRule::order('sort asc,id asc')->select()->toArray();
            $rule = DataManager::channelLevel($rule, '', '', 'path', 'pid');
            $authRule = $this->getAuthRule($rule);
            $rules = $info['rule'] ? $info['rule'] : [];
            $builder = new FormBuilder;
            $data = $builder
                ->setMethod('put')
                ->addRow('title', 'custom', '角色名称', '', [
                    'type'                              => 'info-text',
                ])
                ->addRow('rule', 'tree', '权限授权', $rules, [
                    'data'                      => $authRule,
                    'showCheckbox'              => true,
                    'defaultExpandAll'          => true
                ])
                ->setFormData($info)
                ->create();
            return Json::successRes($data);
        }
    }

    /**
     * 获取权限列表
     *
     * @param array $rule
     * @return array
     */
    public function getAuthRule(array $rule): array
    {
        $list = [];
        $i = 0;
        foreach ($rule as $value) {
            $list[$i]['title']          = $value['title'];
            $list[$i]['id']             = $value['path'];
            $list[$i]['level']          = $value['_level'];
            if ($value['_data']) {
                $list[$i]['children']   = $this->getAuthRule($value['_data']);
            }
            $i++;
        }
        return $list;
    }
}
